<?php

// +----------------------------------------------------------------------
// | MC PHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------


namespace app\api\controller\v1;

use app\api\controller\Base;
use app\common\service\ApiReturn;
use think\facade\Db;
use app\common\model\Order;
/**
 * @Author: Bryant
 * @Date: 2023-06-07 10:41:48
 * @method post
 * @title 支付
 */
class Pay extends Base
{
    /**
     * @Author: Bryant
     * @Date: 2023-06-12 16:51:52
     * @method post
     * @title 余额支付
     */
    public function  balancePay($data=[], $user=[])
    {
        $order = Db::name('order')->where(['order_sn'=>$data['order_sn']])->find();
        if (!$order) {
            return ApiReturn::r(0, '', '订单不存在');
        }
        if ($order['pay_status'] == 1) {
            return ApiReturn::r(0, '', '订单已支付，请勿重复支付');
        }
        $user = Db::name('user')->where('id', $user['id'])->find();
        // 判断支付密码 是否存在
        if (!$user['pay_password']) {
            return ApiReturn::r(-2, [], '未设置支付密码');
        }
        // 验证支付密码
        if (password($data['pay_password']) != $user['pay_password']) {
            return ApiReturn::r(0, [], '支付密码错误！');
        }
        //查询用户资产
        $user_assets = Db::name('user_assets')->where('user_id',$user['id'])->find();
        if ($user_assets['user_money'] < $order['payable_money']) {
            return ApiReturn::r(-1, '', '可用余额不足');
        }
        // 获取支付编号
        $paysnLog = $this->getPaysn($order);

        Db::startTrans();
        try {
            // 记录日志
            $moneyLogService = new \app\service\user\UserMoneyLog();
            $moneyLogService->changeMoney($user['id'], -$order['payable_money'], 6, '余额支付', $data['order_sn']);
            $verifyService = new \app\service\order\Verify;
            $res = $verifyService->verify($paysnLog->pay_sn, 'wallet', [], '', $order['payable_money']);
            if (!$res) {
                throw new \Exception(lang('pay.payment_failed'));
            }
            Db::commit();
        } catch (\Exception $e){
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, [], '支付成功');
    }
    /**
     * @Author: Bryant
     * @Date: 2023-06-07 10:42:39
     * @method post
     * @title 获取微信开放平台预支付订单
     */
    public function getWxpay($data)
    {
        //处理平台自己的订单
        $order = Order::where("order_sn", $data['order_sn'])->find();
        if (!$order) {
            return ApiReturn::r(0, [], '订单不存在');
        }
        if ($order['pay_status'] > 0) {
            return ApiReturn::r(0, [], '该订单支付状态已发生改变');
        }
        if ($order['pay_type'] == 'alipay') {
            return ApiReturn::r(0, [], '请使用发起支付宝支付接口');
        }
        if ($order['pay_type'] == 'appleiap') {
            return ApiReturn::r(0, [], '请使用发起苹果支付接口');
        }
        // 获取支付编号
        $paysnLog = $this->getPaysn($order);
        $data_pay = array(
            'body' => Order::$orderTypes[$order['order_type']],
            'total_fee' => $order['payable_money'],
            // 'total_fee' => 0.01,
            'out_trade_no' => $paysnLog,
        );

        Db::startTrans();
        try {
            switch ($data['wxpaytype']) {
                case 'apppay':
                    $arr = addons_action('WeChat', 'AppPay', 'pay', [$data_pay]);
                    break;
                case 'minipay':
                    $data_pay['xcx_openid'] = Db::name('user_third')->where('user_id', $order['user_id'])->where('type','wx_xcx')->value('openid');
                    if (!$data_pay['xcx_openid']) {
                        exception('获取小程序openid失败');
                    }
                    $arr = addons_action('WeChat', 'MiniPay', 'pay', [$data_pay]);
                    break;
                case 'codepay':
                    $data_pay['gzh_openid'] = Db::name('user_third')->where('user_id', $order['user_id'])->where('type','wx_native')->value('openid');
                    if (!$data_pay['gzh_openid']) {
                        exception('获取公众号openid失败');
                    }
                    $arr = addons_action('WeChat', 'CodePay', 'pay', [$data_pay]);
                    break;
                default:
                    $arr = addons_action('WeChat', 'AppPay', 'pay', [$data_pay]);
                    break;
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, [], '调取支付失败' . $e->getMessage());
        }

        return ApiReturn::r(1, $arr, '请按照此配置调起支付');
    }

    /**
     * @Author: Bryant
     * @Date: 2023-06-07 15:42:51
     * @method post
     * @title 获取支付宝预支付订单
     */
    public function getAlipay($data)
    {
        //处理平台自己的订单
        $order = Order::where(["order_sn"=>$data['order_sn']])->find();
        if (!$order) {
            return ApiReturn::r(0, [], '订单不存在');
        }
        if ($order['pay_status'] > 0) {
            return ApiReturn::r(0, [], '该订单支付状态已发生改变');
        }

        if ($order['pay_type'] =='wxpay') {
            return ApiReturn::r(0, [], '请使用发起微信支付接口');
        }

        if ($order['pay_type'] =='appleiap') {
            return ApiReturn::r(0, [], '请使用发起苹果支付接口');
        }
        // 获取支付编号
        $paysnLog = $this->getPaysn($order);
        $data = array(
            'subject' => Order::$orderTypes[$order['order_type']],
            'body' => Order::$orderTypes[$order['order_type']],
            'out_trade_no' => $paysnLog,
            'total_amount' => $order['payable_money'],
            'notify_url'=> sysconfig('site','site_domain').'/notify/ali/alipay'
        );
        try {
            $string = addons_action('Alipay', 'Aop', 'AlipayTradeAppPayRequest', [$data]);
        } catch (\Exception $e) {
            return ApiReturn::r(0, [], '调取支付失败' . $e->getMessage());
        }

        if ($string) {
            return ApiReturn::r(1, $string, '请按照此配置调起支付');
        }
        return ApiReturn::r(0,[], '调取支付失败');
    }

    /**
     * @notes: 获取支付编号
     * @param $order
     * @time: 2024/1/27 16:23
     */
    protected function getPaysn($order) {
        $paysnLog = \app\admin\model\order\PaysnLog::where('order_id', $order['id'])
            ->find();
        if (!$paysnLog) {
            $paysn = \util\SnowFlake::generateParticle();
            $paysnLog = \app\admin\model\order\PaysnLog::create([
                'order_id' => $order['id'],
                'user_id' => $order['user_id'],
                'pay_fee' => $order['payable_money'],
                'pay_sn' => $paysn,
                'type' => 'full',
            ]);
        }
        return $paysnLog;
    }
}